/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "pca9545.h"
#include <mc/exception.h>

using namespace dev;

bool chip_pca9545::init(mc::mutable_dict& csr_object) {
    try {
        // 调用chip_base的init函数
        chip_base::init(csr_object);
        // 从字典中提取各个属性值并设置到对象中
        if (csr_object.contains("ChannelNum")) {
            this->m_channel_num = csr_object["ChannelNum"].as<uint8_t>();
        }
    } catch (const std::exception& e) {
        elog("PCA9545 configuration loading failed: ${error}", ("error", e.what()));
        return false;
    }

    return true;
}

int32_t chip_pca9545::open_channel(std::shared_ptr<bus_base> bus) {
    // 当bus为nullptr时抛出异常
    if (!bus) {
        MC_THROW(mc::invalid_op_exception, "Pca9545 bus select failed: bus object cannot be null");
    }

    // 使用bus对象的ID来决定选择哪个通道
    uint8_t bus_id = bus->get_id();

    uint8_t              write_reg  = 1 << bus_id;
    std::vector<uint8_t> buffer_vec = {write_reg};
    std::vector<uint8_t> empty_buffer;

    try {
        std::string error;
        int32_t ret = block_write(0, buffer_vec, empty_buffer, error);
        if (ret != HAS_OK) {
            MC_THROW(mc::invalid_op_exception, "Pca9545 bus select failed: ${error}",
                     ("error", error));
        }
    } catch (const std::exception& e) {
        MC_THROW(mc::invalid_op_exception, "Pca9545 bus select failed, exception: ${exception}",
                 ("exception", e.what()));
    }

    return HAS_OK;
}